package org.sction.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 作者 : sorc
 * @version 创建时间：2012-3-20 下午2:35:26
 * 
 *          类说明
 */
public class DateUtils {
	public static final String DATETIME = "yyyy-MM-dd HH:mm:ss";
	public static final String DATE = "yyyy-MM-dd";
	public static final String TIME = "HH:mm:ss";

	public static String Date2String(Date date, String style) {
		try {
			DateFormat df = new SimpleDateFormat(style);
			return df.format(date);
		} catch (Exception e) {
			return null;
		}
	}

	public static String DateTime2String(Date date) {
		return Date2String(date, DATETIME);
	}

	public static String Date2String(Date date) {
		return Date2String(date, DATE);
	}

	public static String Time2String(Date date) {
		return Date2String(date, TIME);
	}

	public static Date String2Date(String date, String style)
			throws ParseException {
		DateFormat df = new SimpleDateFormat(style);
		try {
			return df.parse(date);
		} catch (Exception e) {
			return null;
		}
	}

	public static Date String2DateTime(String date) {
		try {
			return String2Date(date, DATETIME);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Date String2Date(String date) {
		try {
			return String2Date(date, DATE);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Date String2Time(String date) {
		try {
			return String2Date(date, TIME);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Date StringAutoCast(String date) throws ParseException {
		String style = "";
		Pattern p = Pattern.compile("\\W");
		Matcher m = p.matcher(date);
		String[] styles = { "yyyy", "MM", "dd", "HH", "mm", "ss", "SSS" };
		int i = 0;
		boolean isTime = false;
		for (; i < styles.length - 1 && m.find(); i++) {
			String sp = m.group();
			if (sp.equals(":") && !isTime) {
				isTime = true;
				i = 3;
			}
			style += styles[i] + sp;
		}
		style += styles[i];
		return String2Date(date, style);
	}

	public static void main(String[] args) {
		// String date = "1999/01-12 15:20:55:980";
	}
}
